/**
 * @file 数据详情
 * @author liushuang04@baijaihulian.com
 * @date 2019-11-19
 */

import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {Table} from 'antd';
import './index.styl';
import shortid from 'shortid';

// 分页配置
const customPagination = (pagination, handlePageChange) => {
    if (pagination) {
        if (pagination.pageNum) {
            pagination.current = pagination.pageNum;
            pagination.total = pagination.count;
        }
        // 更改size
        pagination.defaultPageSize = pagination.pageSize || 20;
        pagination.pageSizeOptions = ['10', '20', '50', '100'];
        pagination.showSizeChanger = true;
        // pageSize 变化
        pagination.onShowSizeChange = (current, size) => handlePageChange(1, size);

        // 快速跳转
        // pagination.showQuickJumper = true;
        // 用于显示数据总量和当前数据顺序
        // pagination.showTotal = (total, range) => `共 ${total} 条数据`;
        // 页码改变
        pagination.onChange = (page, size) => handlePageChange(page, size);

        return pagination;
    }
    return false;
};

class WrapTable extends Component {
    static propTypes = {
        isLoading: PropTypes.bool.isRequired,
        columns: PropTypes.arrayOf(PropTypes.object).isRequired,
        dataSource: PropTypes.arrayOf(PropTypes.object).isRequired,
        rowKey: PropTypes.oneOfType([PropTypes.string, PropTypes.func])
    };

    constructor(props) {
        super(props);
        this.tableRef = React.createRef();
        this.state = {
            scroll: null,
            pagination: false,
        };
    }

    static getDerivedStateFromProps(props, state) {
        const {
            dataSource,
            onPageChange,
            scroll,
        } = props;
        let {pagination = false} = props;
        pagination = customPagination(pagination, onPageChange);
        if (scroll) {
            state.scroll = scroll;
        }
        return {
            dataSource,
            pagination,
            scroll,
        };
    }

    render() {
        const {
            rowKey,
            isLoading,
            columns,
            dataSource,
            ...rest
        } = this.props;
        return (
            <div className="table-main" ref={this.tableRef}>
                <Table
                    rowKey={rowKey}
                    loading={isLoading}
                    columns={columns}
                    dataSource={dataSource}
                    {...this.state}
                    {...rest}
                />
            </div>
        );
    }
}

WrapTable.defaultProps = {
    rowKey: () => shortid.generate()
};

export default WrapTable;
